package com.yxc.eslibrary.http;

import android.os.AsyncTask;
import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created by robin on 15-9-7.
 */
public class HttpTask extends AsyncTask<String, Integer, HttpResponse> {

    public static final String TAG = "HttpTask";

    private int timeout = 6000;

    HttpHeader[] headers;
    HttpMethod method;
    IHttpParams params;
    String url;
    HttpCallBack callBack;

    public HttpTask(HttpMethod method, HttpHeader[] headers, IHttpParams params, String url, HttpCallBack callBack) {
        this.method = method;
        this.headers = headers;
        this.params = params;
        this.url = url;
        this.callBack = callBack;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected HttpResponse doInBackground(String... params) {
        if (callBack!=null){
            callBack.requestStarted();
        }
        HttpResponse response = new HttpResponse();
        String result = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try {
            //添加公共参数
            this.params.addParams(CommonParams.getCommonParams());

            URL url = new URL(setUpURL());
            connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(timeout);

            if (method==HttpMethod.POST){
                connection.setDoOutput(true);// 是否输入参数
                connection.setDoInput(true);
                connection.setUseCaches(false);
                byte[] bytes = this.params.formatParams().getBytes();
                connection.getOutputStream().write(bytes);
                connection.setRequestProperty("contentType", "application/x-www-form-urlencoded");
                connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            }

            if (headers!=null){
                for (HttpHeader header: headers){
                    connection.setRequestProperty(header.getKey(), header.getValue());
                }
            }
            //添加公共头信息
            for (HttpHeader header: CommonParams.getCommonHeaders()){
                connection.setRequestProperty(header.getKey(), header.getValue());
            }

            connection.setRequestProperty("Accept-Encoding", "gzip");

            Log.d(TAG, "" + connection.getResponseCode() + " : " + connection.getResponseMessage());
            response.setCode(connection.getResponseCode());
            response.setMessage(connection.getResponseMessage());

            InputStream bis = new BufferedInputStream(connection.getInputStream());
            String encoding = connection.getContentEncoding();
            if(encoding!=null && encoding.contains("gzip")){//首先判断服务器返回的数据是否支持gzip压缩，
                bis = new GZIPInputStream(bis);	//如果支持则应该使用GZIPInputStream解压，否则会出现乱码无效数据
            }
            in = new InputStreamReader(bis);

            BufferedReader bufferedReader = new BufferedReader(in);
            StringBuffer strBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                strBuffer.append(line);
            }
            result = strBuffer.toString();
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
//            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        response.setResult(result);
        return response;
    }

    @Override
    protected void onPostExecute(HttpResponse response) {
        super.onPostExecute(response);
        if (callBack!=null){
            if (response.getCode()!=200){
                callBack.requestFailed(response);
            }else {
                callBack.requestSucceed(response.getResult());
            }
        }
    }


    /**
     * Method为GET时，处理url
     * @return  处理之后的URL
     */
    private String setUpURL(){
        String urlStr = this.url;
        if (method==HttpMethod.GET){
            String paramsStr = this.params.formatParams();
            if (this.url.contains("?")){
                if (this.url.endsWith("?")){
                    urlStr += paramsStr;
                }else{
                    if (this.url.endsWith("&")){
                        urlStr += paramsStr;
                    }else{
                        urlStr += ("&"+paramsStr);
                    }
                }
            }else{
                urlStr += ("?"+paramsStr);
            }
        }
        return urlStr;
    }
}
